<template>
	<view
		class="layout"
		:style="{
			paddingTop: paddingTop,
			backgroundImage: 'url(' + pageBgImage + ')'
		}"
	>
		<view class="layout-main">
			<view class="layout-main-avatar">
				<image :src="isNew ? agentInfo.agentImg : userAvatar" />
				<text>{{ isNew ? agentInfo.agentName : '达人营注册' }}</text>
			</view>
			<image v-if="isNew" src="@/static/images/my/img_register_invite.png" class="remind-image" />
			<view
				class="layout-main-content"
				:style="{
					backgroundImage: 'url(' + pageMainImage + ')'
				}"
			>
				<view class="layout-main-content-exhibit">
					<view :key="index" v-for="(item, index) in mainExhibitList" class="layout-main-content-item mainExhibitList">
						<view class="layout-main-content-item-left">
							{{ item.label }}
						</view>

						<view class="layout-main-content-item-right">
							{{ exhibiParams[item.type] || '' }}
						</view>
					</view>
				</view>

				<template>
					<view :key="index" v-for="(item, index) in mainContentList" class="layout-main-content-item">
						<view class="layout-main-content-item-left">
							{{ item.label }}
						</view>

						<view class="layout-main-content-item-right">
							<input
								type="text"
								:disabled="item.isSelect"
								:placeholder="item.placeholder"
								placeholder-class="placeholder"
								v-model="contentParams[item.type]"
								@click="changeSelectValue(item, index)"
							/>
							<image v-if="item.icon" :src="item.icon" />
						</view>
					</view>
				</template>
			</view>
		</view>

		<BottomActionSheet
			v-model="isPopup"
			:title="popupTitle"
			:list="actionSheetlList"
			:otherParams="actionSheetOtherParams"
			:activeValue="actionSheetActive"
			@changeBottomActionSheet="changeBottomActionSheet"
		/>

		<view class="layout-footer">
			<button :disabled="isLoading" :loading="isLoading" @click="userRegister" :class="{ active: isLoading }">注册</button>
		</view>

		<!-- 承诺书 -->
		<view class="layout-commitment">
			<view @click="changeIsCommitment">
				<image :src="commitmentIconObject[isCommitment ? 'active' : 'default']" />
				我已阅读并同意
			</view>
			<button @click.prevent="openCommitment">《承诺书》</button>
		</view>
	</view>
</template>

<script>
import { setBatchSave } from '@/api/login';
import { getLocal, setLocal } from '@/utils';
import srorageKey from '@/utils/srorage/key';
import { getSystemInfo, defaultImageUrl } from '@/utils';
import { getAreaCode, getListAccountType } from '@/api/common';
import { registerAndBindUrl } from '@/api/other';
import BottomActionSheet from '@/components/bottomActionSheet';
const iconDown = Object.freeze(`${defaultImageUrl}icon/icon_register_down.png`);
const pageBgImage = Object.freeze(`${defaultImageUrl}image/img_register_bg.png`);
const pageMainImage = Object.freeze(`${defaultImageUrl}image/img_register_shape.png`);

const commitmentIconObject = Object.freeze({
	default: require('@/static/icon/icon_register_agree_default.png'),
	active: require('@/static/icon/icon_register_agree_active.png')
});

const mainExhibitList = Object.freeze([
	{
		type: 'channelType',
		label: '推广平台：'
	},
	{
		type: 'nickName',
		label: '平台昵称：'
	},
	{
		type: 'channelAccount',
		label: '平台号：'
	},
	{
		type: 'followerCount',
		label: '粉丝数：'
	}
]);

const mainContentList = [
	{
		type: 'accountValue',
		label: '账号类别',
		icon: iconDown,
		isSelect: true,
		activeValue: [],
		placeholder: '请选择账号类别'
	},
	{
		type: 'locationValue',
		label: '所在位置',
		icon: iconDown,
		isSelect: true,
		activeValue: [],
		placeholder: '请选择所在省市'
	}
];

const { platform, statusBarHeight } = getSystemInfo();

export default {
	name: 'InfoRegistration',

	data() {
		return {
			pageBgImage,
			pageMainImage,
			commitmentIconObject,
			isCommitment: false,

			mainExhibitList,
			mainContentList,

			isPopup: false,
			isLoading: false,

			exhibiParams: {},
			contentParams: {
				accountValue: '',
				locationValue: ''
			},

			popupTitle: '',
			actionSheetlList: [],
			actionSheetActive: [],
			actionSheetOtherParams: {},
			agentInfo: {
				agentImg: '',
				agentName: ''
			},
			getAUserId: '',
			getPhone: ''
		};
	},

	computed: {
		userAvatar() {
			const { headUrl } = getLocal(srorageKey.userInfo) || {};

			return headUrl;
		},

		paddingTop() {
			return `${statusBarHeight + (platform === 'ios' ? 44 : 48)}px`;
		},
		isNew() {
			const { getAUserId = '', agentInfo = {} } = this;
			const { agentImg = '', agentName = '' } = agentInfo;
			console.log(getAUserId, agentName, agentImg);
			return getAUserId && agentImg && agentImg;
		}
	},

	onLoad(params) {
		const { type, nickName, followerCount, byteDanceId, aUserId = '', agentImg = '', agentName = '', phone = '' } = params || {};

		if (aUserId) {
			this.getAUserId = aUserId;
			this.agentInfo = {
				agentImg,
				agentName
			};
		}
		if (phone) {
			this.getPhone = phone;
		}
		this.exhibiParams = {
			type,
			nickName,
			followerCount,
			channelAccount: byteDanceId,
			channelType: type.split('-')[0]
		};

		this.getSelectData();
	},

	methods: {
		changeIsCommitment() {
			this.isCommitment = !this.isCommitment;
		},

		changeSelectValue(params, index) {
			const { icon, activeValue, list, placeholder } = params;

			if (!icon) {
				return;
			}

			this.popupTitle = placeholder;
			this.actionSheetlList = list;
			this.actionSheetOtherParams = {
				...params,
				index
			};
			this.actionSheetActive = activeValue.map((item) => item.index);
			this.isPopup = true;
		},

		getSelectData() {
			Promise.all([getListAccountType(), getAreaCode()]).then((res) => {
				const [accountList, areaList] = res;

				const filterAccountList = (accountList?.data || []).map((item) => {
					const { value, desc } = item;

					return {
						value: value,
						label: desc
					};
				});
				const paramsObject = {
					accountValue: filterAccountList,
					locationValue: areaList?.data[0]?.children || []
				};

				this.mainContentList = this.mainContentList.map((item) => {
					return {
						...item,
						list: paramsObject[item.type]
					};
				});
			});
		},

		changeBottomActionSheet(value, otherParams) {
			const { type, index } = otherParams;
			const filtersValue = value.map((item) => item.label).join('-');

			this.contentParams = {
				...this.contentParams,
				[type]: filtersValue
			};

			this.$set(this.mainContentList[index], 'activeValue', value);
		},

		userRegister() {
			const {
				mainContentList,
				contentParams,
				isCommitment,
				exhibiParams: { channelAccount, followerCount, nickName, type }
			} = this;

			const status = mainContentList.some((item) => {
				if (contentParams[item.type].replace(/\s/g, '') === '') {
					uni.showToast({
						mask: true,
						icon: 'none',
						title: item.placeholder
					});

					return true;
				}
			});

			if (status) {
				return;
			}

			if (!isCommitment) {
				uni.showToast({
					mask: true,
					icon: 'none',
					title: '请先阅读并同意承诺书'
				});

				return;
			}

			const userInfo = getLocal(srorageKey.userInfo) || {};
			const params = {
				nickName,
				channelAccount,
				channelFens: followerCount,

				mobile: userInfo.phone ? userInfo.phone : this.getPhone || '',
				channelType: type.split('-')[1],
				accountType: mainContentList[0].activeValue[0].value,
				province: mainContentList[1].activeValue[0].value,
				city: mainContentList[1].activeValue[1].value
			};
			let newParams = {};
			const { agentImg = '', agentName = '' } = this.agentInfo || {};
			if (this.getAUserId && agentImg && agentName) {
				newParams = Object.assign(params, { aUserId: this.getAUserId });
			}
			console.log(newParams);
			this.isLoading = true;

			if (this.getAUserId && agentImg && agentName) {
				registerAndBindUrl(newParams)
					.then((res) => {
						console.log(res);
						const { code } = res;

						if (code !== 200) {
							return;
						}

						setLocal(srorageKey.userInfo, {
							...userInfo,
							channelCount: 1
						});

						uni.switchTab({
							url: '/pages/tabBar/Index'
						});
					})
					.finally(() => {
						this.isLoading = false;
					});
			} else {
				setBatchSave([params])
					.then((res) => {
						const { code } = res;

						if (code !== 200) {
							return;
						}

						setLocal(srorageKey.userInfo, {
							...userInfo,
							channelCount: 1
						});

						uni.navigateBack({
							delta: 2
						});
					})
					.finally((e) => {
						this.isLoading = false;
					});
			}
		},

		openCommitment() {
			const webView = `${defaultImageUrl}webView/Commitment.html`;
			const url = `/tandianPage/CommonWebView?webView=${webView}`;

			uni.navigateTo({
				url
			});
		}
	},

	components: {
		BottomActionSheet
	}
};
</script>

<style lang="scss" scoped>
@import './components/channelCommon.scss';

.layout {
	overflow-y: scroll;
	padding-bottom: 10px;
	&-main {
		&-content {
			height: 798rpx;
			background-size: 100% 798rpx;
			overflow-y: scroll;
			&-exhibit {
				height: 308rpx;
				padding: 32rpx;
				background: #f6f6f6;
				border-radius: 24rpx;

				.layout-main-content-item {
					height: 40rpx;
					min-height: 40rpx;
					margin-top: 28rpx;

					view {
						height: 40rpx;
						line-height: 40rpx;
					}

					&:first-child {
						margin-top: 0;
					}

					&.mainExhibitList {
						.layout-main-content-item-left {
							color: #999;
						}

						.layout-main-content-item-right {
							color: #333;
						}
					}
				}
			}

			&-item-right {
				font-size: 26rpx;
			}
		}
	}

	&-commitment {
		margin-top: 32rpx;
		padding: 0 60rpx;

		display: flex;
		align-items: center;

		color: #666;
		font-size: 24rpx;

		view {
			display: flex;
			align-items: center;

			image {
				width: 40rpx;
				height: 40rpx;
				margin-right: 2rpx;
			}
		}

		button {
			color: #487fff;
			font-size: 24rpx;
			padding: 0;
			margin: 0;
			height: 32rpx;
			line-height: 32rpx;

			&::after {
				display: none;
			}

			&:active {
				background: transparent;
			}
		}
	}
}
.remind-image {
	width: 100%;
	height: 160rpx;
	margin: 0 20rpx;
}
</style>
